package cn.liuweiwei.util;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator.Builder;
import com.auth0.jwt.algorithms.Algorithm;

public class JWTUtils {

    private static final String SING = "@￥%……HUIYBNU**(HNKJJPM:784654689";

    // 过期时间 默认 7 天
    private static int expiryTime = 7;

    private JWTUtils() {
    }

    // 设置 token 过期时间 默认 7 天
    public static void setExpiryTime(int day) {
        expiryTime = day;
    }

    // 获得 token
    public static String getToken(Map<String, String> map) {
        Builder builder = JWT.create();
        builder.withExpiresAt(getTime(expiryTime));
        if (!Objects.isNull(map)) {
            setPayLoad(map, builder);
        }
        return builder.sign(Algorithm.HMAC256(SING));
    }

    private static Date getTime(int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, day);
        return calendar.getTime();
    }

    private static void setPayLoad(Map<String, String> map, Builder builder) {
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
    }

    // 验证 token 的合法性
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(SING)).build().verify(token);
    }

    // 验证并获得 token 信息
    public static String getTokenInfo(String token, String key) {
        return JWT.require(Algorithm.HMAC256(SING)) //
                .build().verify(token) //
                .getClaim(key).asString();
    }

}
